import 'package:flutter/material.dart';
import 'package:wan_android/api/fav.dart';
import 'package:wan_android/model/fav/fav_type.dart';

class FavPageModel extends ChangeNotifier {
  int page = 0;
  List<FavItemData> _favList = [];

  List<FavItemData> get favList => _favList;

  // 收藏文章
  Future setFavArticle(int id) async {
    Map<String, dynamic> response = await setFav(id);
    CommonFav commonFav = CommonFav.fromJson(response);
    if (commonFav.errorCode == 0) {
      // 收藏成功，将文章ID更新存储到用户信息中(本地存储及状态)
      return true;
    }
    return false;
  }

  // 取消收藏文章
  Future cancelFavArticle(int id) async {
    Map<String, dynamic> response = await cancelFav(id);
    CommonFav commonFav = CommonFav.fromJson(response);
    if (commonFav.errorCode == 0) {
      // 取消收藏成功，将文章ID从用户信息中(本地存储及状态)更新删除
      return true;
    }
    return false;
  }

  // 分页获取收藏页面的收藏列表数据
  Future getFavPageList(bool loadMore) async {
    if (loadMore) {
      page++;
      Map<String, dynamic> response = await getFavList(page);
      FavListResp favListResp = FavListResp.fromJson(response);

      if (favListResp.data != null && favListResp.data.datas != null) {
        _favList.addAll(favListResp.data.datas);
      } else {
        _favList = [];
      }
    } else {
      page = 0;
      Map<String, dynamic> response = await getFavList(page);
      FavListResp favListResp = FavListResp.fromJson(response);

      _favList.clear();
      if (favListResp.data != null && favListResp.data.datas != null) {
        _favList = favListResp.data.datas;
      } else {
        _favList = [];
      }
    }
    notifyListeners();
  }

  // 收藏页面的取消收藏
  removeFavOfPage(int id) {
    _favList.removeWhere((item) => item.id == id);
    notifyListeners();
  }
}